<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>AR诗词扫描</title>
    <script src="https://cdn.jsdelivr.net/npm/mind-ar@1.2.3/dist/mindar-image.prod.js"></script>
    <script src="https://aframe.io/releases/1.4.0/aframe.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/mind-ar@1.2.3/dist/mindar-image-aframe.prod.js"></script>
    <!-- 引入 vConsole -->
    <script src="https://unpkg.com/vconsole@latest/dist/vconsole.min.js"></script>
    <!-- 使用草书字体 -->
    <link href="https://fonts.googleapis.cn/css2?family=Ma+Shan+Zheng&family=ZCOOL+QingKe+HuangYou&display=swap" rel="stylesheet">
    <style>
        body {
            margin: 0;
            padding: 0;
            background: #000;
            overflow: hidden;
            width: 100vw;
            height: 100vh;
        }
        a-scene {
            width: 100% !important;
            height: 100% !important;
        }
        #textCanvas {
            display: none;
        }
        /* 字体预加载 */
        .font-loader {
            position: absolute;
            left: -1000px;
            visibility: hidden;
            font-family: 'Ma Shan Zheng', cursive;
            font-family: 'ZCOOL QingKe HuangYou', cursive;
        }
    </style>
</head>
<body>

<!-- 字体预加载 -->
<div class="font-loader">静夜思床前明月光疑是地上霜举头望明月低头思故乡</div>

<canvas id="textCanvas" width="1200" height="800"></canvas>

<a-scene
        mindar-image="imageTargetSrc: ./models/card.mind; autoStart: true;"
        embedded
        vr-mode-ui="enabled: false"
        loading-screen="enabled: false">

    <a-camera active="true" position="0 0 0"></a-camera>

    <a-entity mindar-image-target="targetIndex: 0">
        <!-- 诗词容器 -->
        <a-entity id="poem-container" position="0 0 0"></a-entity>
    </a-entity>

</a-scene>

<script>
    // 初始化 vConsole
    var vConsole = new VConsole();
    console.log('🚀 AR诗词扫描启动...');

    const target = document.querySelector('[mindar-image-target]');
    const poemContainer = document.querySelector('#poem-container');

    // 李白《静夜思》- 五言绝句
    const poem = {
        title: "静夜思",
        author: "〔唐〕李白",
        lines: [
            "床前明月光，",
            "疑是地上霜。",
            "举头望明月，",
            "低头思故乡。"
        ]
    };

    let currentPosition = 0;
    let poemAnimation = null;

    // 草书字体列表
    const cursiveFonts = [
        'Ma Shan Zheng',           // 马善政草书
        'ZCOOL QingKe HuangYou',   // 站酷庆科黄油体
        'STXingkai',               // 华文行楷
        'sans-serif'               // 备用
    ];

    // 检测可用草书
    function getAvailableCursiveFont() {
        const canvas = document.getElementById('textCanvas');
        const ctx = canvas.getContext('2d');
        const testText = "静夜思";

        for (let font of cursiveFonts) {
            try {
                ctx.font = `bold 80px "${font}"`;
                const metrics = ctx.measureText(testText);

                if (metrics.width > 0) {
                    console.log(`✅ 使用草书: ${font}`);
                    return font;
                }
            } catch (e) {
                console.log(`❌ 字体不可用: ${font}`);
            }
        }
        return 'sans-serif';
    }

    // 生成黑色草书文字图片
    function generateCharacterImage(character, fontSize = 120, color = '#000000') {
        const canvas = document.getElementById('textCanvas');
        const ctx = canvas.getContext('2d');

        ctx.clearRect(0, 0, canvas.width, canvas.height);

        const fontName = getAvailableCursiveFont();

        // 草书样式 - 黑色，带轻微阴影增强立体感
        ctx.fillStyle = color;
        ctx.font = `bold ${fontSize}px "${fontName}"`;
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';

        // 轻微阴影让草书更清晰
        ctx.shadowColor = 'rgba(0, 0, 0, 0.3)';
        ctx.shadowBlur = 4;
        ctx.shadowOffsetX = 2;
        ctx.shadowOffsetY = 2;

        ctx.fillText(character, canvas.width / 2, canvas.height / 2);

        return canvas.toDataURL('image/png');
    }

    // 计算竖排布局位置 - 调整间距
    function calculateVerticalPosition(charInfo) {
        const { char, type, lineIndex, charIndex, index } = charInfo;

        if (type === 'title') {
            // 标题 - 顶部右侧，往右移两个字符间距
            const colX = 0.9;  // 往右移：0.6 → 0.9（增加0.3，约2个字符间距）
            const titleY = 0.8 - (charIndex * 0.25);  // 保持标题间距
            return { x: colX, y: titleY, z: 0, fontSize: 130, color: '#000000' };

        } else if (type === 'author') {
            // 作者 - 标题下方，也往右移
            const colX = 0.6;  // 往右移：0.3 → 0.6
            const authorY = 0.8 - (charIndex * 0.15);
            return { x: colX, y: authorY, z: 0, fontSize: 70, color: '#666666' };

        } else {
            // 诗句 - 从右到左竖排，但显示顺序从左到右
            // 计算列位置：从左到右显示
            const columnIndex = lineIndex;  // 0,1,2,3 从左到右
            const colX = 0.3 - (columnIndex * 0.3);  // 从左开始

            // 减少字间距：0.15 → 0.12（减少一个字符间距）
            const charY = 0.3 - (charIndex * 0.12);

            return {
                x: colX,
                y: charY,
                z: 0,
                fontSize: 100,
                color: '#000000'
            };
        }
    }

    // 获取所有诗词字符（正确顺序：从左到右显示）
    function getAllPoemCharactersCorrectOrder() {
        const characters = [];

        // 先显示第一句（床前明月光，）
        const firstLine = poem.lines[0];
        for (let charIndex = 0; charIndex < firstLine.length; charIndex++) {
            characters.push({
                char: firstLine[charIndex],
                type: 'poem',
                lineIndex: 0,
                charIndex: charIndex,
                index: 0
            });
        }

        // 第二句（疑是地上霜。）
        const secondLine = poem.lines[1];
        for (let charIndex = 0; charIndex < secondLine.length; charIndex++) {
            characters.push({
                char: secondLine[charIndex],
                type: 'poem',
                lineIndex: 1,
                charIndex: charIndex,
                index: 1
            });
        }

        // 第三句（举头望明月，）
        const thirdLine = poem.lines[2];
        for (let charIndex = 0; charIndex < thirdLine.length; charIndex++) {
            characters.push({
                char: thirdLine[charIndex],
                type: 'poem',
                lineIndex: 2,
                charIndex: charIndex,
                index: 2
            });
        }

        // 第四句（低头思故乡。）
        const fourthLine = poem.lines[3];
        for (let charIndex = 0; charIndex < fourthLine.length; charIndex++) {
            characters.push({
                char: fourthLine[charIndex],
                type: 'poem',
                lineIndex: 3,
                charIndex: charIndex,
                index: 3
            });
        }

        // 最后显示标题和作者
        for (let i = 0; i < poem.title.length; i++) {
            characters.push({
                char: poem.title[i],
                type: 'title',
                index: 4,
                charIndex: i,
                lineIndex: 0
            });
        }

        for (let i = 0; i < poem.author.length; i++) {
            characters.push({
                char: poem.author[i],
                type: 'author',
                index: 5,
                charIndex: i,
                lineIndex: 0
            });
        }

        return characters;
    }

    // 开始诗词动画
    function startPoemAnimation() {
        console.log('🎬 开始诗词动画（正确顺序）');
        clearPoem();
        currentPosition = 0;

        const allChars = getAllPoemCharactersCorrectOrder();

        poemAnimation = setInterval(() => {
            if (currentPosition < allChars.length) {
                addNextPoemCharacter(allChars[currentPosition]);
                currentPosition++;
            } else {
                clearInterval(poemAnimation);
                console.log('✅ 诗词动画完成');
            }
        }, 150);
    }

    function stopPoemAnimation() {
        if (poemAnimation) {
            clearInterval(poemAnimation);
            poemAnimation = null;
        }
    }

    function clearPoem() {
        while (poemContainer.firstChild) {
            poemContainer.removeChild(poemContainer.firstChild);
        }
        currentPosition = 0;
    }

    function addNextPoemCharacter(charInfo) {
        const { char, type } = charInfo;
        console.log(`✨ 显示: ${char} (${type})`);

        const position = calculateVerticalPosition(charInfo);
        const charImageUrl = generateCharacterImage(char, position.fontSize, position.color);

        const charPlane = document.createElement('a-plane');
        charPlane.setAttribute('src', charImageUrl);
        charPlane.setAttribute('position', `${position.x} ${position.y} ${position.z}`);

        // 设置大小
        let width, height;
        if (type === 'title') {
            width = 0.8; height = 0.8;
        } else if (type === 'author') {
            width = 0.5; height = 0.5;
        } else {
            width = 0.6; height = 0.6;
        }

        charPlane.setAttribute('width', width);
        charPlane.setAttribute('height', height);
        charPlane.setAttribute('transparent', 'true');
        charPlane.setAttribute('alpha-test', '0.1');
        charPlane.setAttribute('scale', '0.1 0.1 0.1');

        // 动画效果
        charPlane.setAttribute('animation', {
            property: 'scale',
            from: '0.1 0.1 0.1',
            to: '1 1 1',
            dur: 500,
            easing: 'easeOutElastic'
        });

        poemContainer.appendChild(charPlane);
    }

    // 等待字体加载
    function waitForFontsLoad() {
        return new Promise((resolve) => {
            if (document.fonts && document.fonts.ready) {
                document.fonts.ready.then(() => {
                    console.log('✅ 所有草书字体加载完成');
                    resolve();
                });
            } else {
                setTimeout(() => {
                    console.log('⏳ 字体加载等待完成');
                    resolve();
                }, 2000);
            }
        });
    }

    // 事件监听
    target.addEventListener('targetFound', function() {
        console.log('🎯 识别成功！开始诗词动画');
        console.log('📖 显示顺序：从左到右（床前明月光 → 疑是地上霜 → 举头望明月 → 低头思故乡 → 标题作者）');
        startPoemAnimation();
    });

    target.addEventListener('targetLost', function() {
        console.log('📵 目标丢失，停止动画');
        stopPoemAnimation();
        clearPoem();
    });

    // 初始化
    document.addEventListener('DOMContentLoaded', function() {
        console.log('📄 页面加载完成，等待草书字体加载...');
        waitForFontsLoad().then(() => {
            console.log('🎉 诗词动画初始化完成');
            console.log('🖋️ 字体：黑色草书');
            console.log('📐 布局调整：');
            console.log('   - 标题往右移2字符间距');
            console.log('   - 句子字间距减少1字符');
            console.log('   - 显示顺序：从左到右');
        });
    });

</script>
</body>
</html>